package com.unidue.foguing.task_A;

import java.io.IOException;

import org.apache.uima.collection.CollectionException;
import org.apache.uima.jcas.JCas;

import com.unidue.foguing.helper.ReaderHelper;
import com.unidue.foguing.types.*;
/**
 * this class make the documents available to the pipeline.
 * @author foguing
 *
 */
public class Reader_TaskA extends ReaderHelper {

	/**
	 * this method feeds the next document into the pipeline
	 */
	@Override
	public void getNext(JCas jCas) throws IOException, CollectionException {
		final String regex = "\\t";
		// split the line into 6 parts using the tab delimiter
		String[] parts = lines.get(currentLine).split(regex);
		// just make sure that the line is compose in 5 parts
		if(parts.length != 6){
			throw new IOException("this line don't match the normal format: " + lines.get(currentLine));
		}
		
		String tweet = parts[5];
		String [] tweetToArray = tweet.split(" ");
		
		
		// get the subTweet from the whole tweet, the StartWords position and the endWords position
		String subTweet = getTheSubTweet(tweetToArray, parts[2], parts[3]);
		
		//add all gold standard values as annotation
		ActualSentiment actualSentiment = new ActualSentiment(jCas);
		actualSentiment.setSID(Long.parseLong(parts[0]));
		actualSentiment.setUID(Long.parseLong(parts[1]));
		actualSentiment.setStartWordPosition(Integer.parseInt(parts[2]));
		actualSentiment.setEndWordPosition(Integer.parseInt(parts[3]));
		actualSentiment.setNumberOfParts(parts.length);
		actualSentiment.setActualSentiment(parts[4]);
		actualSentiment.setSubTweet(subTweet);
		actualSentiment.addToIndexes();
		
		// add the actual document in the jcas
		jCas.setDocumentText(tweet);
		
		
		currentLine++;
	}
	
	/**
	 * this mehtod just take an array that contains all components of the line and retrieve 
	 * from that the subtweet
	 * @param str
	 * @param startPosition
	 * @param endPosition
	 * @return the subTweet of the tweetMessage given a startPosition and a endPosition
	 */
	private String getTheSubTweet(String[] document , String startPosition , String endPosition ){
		String subTweet = "";
		int firstPosition = Integer.parseInt(startPosition);
		int lastPosition = Integer.parseInt(endPosition);
		//as some offsets are not correct, just make sure the tweet will always be analysed.
		if(lastPosition >= document.length){
			for(int i = firstPosition; i < document.length; i++){
				subTweet += document[i] + " ";
			}
		}else{
			for (int i = firstPosition; i <= lastPosition; i++) {
				subTweet += document[i] + " ";
			}
		}
		return subTweet;
	}

}
